package concurrencyPractice.chapter06;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.http.HttpRequest;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

/**
 * @author xinya
 * @version 1.0
 * @project javacore
 * @description 程序6-5 为每个请求启动一个新线程的 Executor
 * @date 2024/1/3 10:14:37
 */
public class ThreadPerTaskExecutor implements Executor {
    @Override
    public void execute(Runnable command) {
        new Thread(command).start();
    }
}

/**
 * 程序6-6 在调用栈中以同步的方式执行所有任务的 Executor
 */
class WithinThreadExecutor implements Executor{

    @Override
    public void execute(Runnable command) {
        command.run();
    }
}

/**
 * 程序6-8 支持关闭操作的 web服务器
 */
class LifeCycleWebServer {

    private final ExecutorService exec = Executors.newFixedThreadPool(100);

    public void start() throws IOException {
        ServerSocket socket = new ServerSocket(80);
        while (!exec.isShutdown()) {
            try {
                final Socket connection = socket.accept();
                exec.execute(new Runnable() {
                    @Override
                    public void run() {
//                    handleRequest(connection);
                    }
                });
            } catch (RejectedExecutionException e) {
                if(!exec.isShutdown()) {
//                    log("task submission rejected", e);
                }
            }
        }
    }

    public void stop(){
        exec.shutdown();
    }
    void handleRequest(Socket connection) {
//        HttpRequest req = readRequest(connection);
//        if(isShutdownRequest(req)) {
//            stop();
//        } else {
//            dispatcherRequest(req);
//        }
    }
}
